# -*- coding:utf-8 -*-
# @FileName :views_api.py
# @user chunxiangjie
# @Time :2022/3/20 19:07
from api_App.models import *
# Create your views here.
import time
from django.http import HttpResponse
import logging
import json
from api_App.view_send_api import Send_Api

logger = logging.getLogger('django')


# 获取配置
def get_apis(request):
    pro_ject_id = request.GET['pro_ject_id']
    apis = list(DB_case_set.objects.filter(project_id=pro_ject_id).values())
    for i in apis:
        i['children'] = eval(i['children'])
    return HttpResponse(json.dumps(apis), content_type='application/json')


def get_apis(request):
    project_id = request.GET['pro_ject_id']
    apis = list(DB_case_set.objects.filter(project_id=project_id).values())
    for i in apis:
        i['children'] = eval(i['children'])
        i['params'] = eval(i['params'])
        i['headers'] = eval(i['headers'])
        i['payload_fd'] = eval(i['payload_fd'])
        i['payload_xwfu'] = eval(i['payload_xwfu'])
    return HttpResponse(json.dumps(apis), content_type='application/json')


# 获取默认勾选配置列表
def get_dck(request):
    pro_ject_id = request.GET['pro_ject_id']
    dck = DB_project_list.objects.filter(id=pro_ject_id)[0].dck.split(',')
    return HttpResponse(json.dumps(dck), content_type='application/json')


# 设置dck
def set_dck(request):
    project_id = request.GET['pro_ject_id']
    dck = request.GET['dck']
    DB_project_list.objects.filter(id=project_id).update(dck=dck)
    return get_dck(request)


# 新增空白接口
def add_apis(request):
    project_id = request.GET['pro_ject_id']
    creat_ime = time.strftime('%Y-%m-%d %H:%M')
    new_api = DB_case_set.objects.create(project_id=project_id, create_time=creat_ime)
    new_api.save()
    return get_apis(request)


# 删除接口和配置
def remove_ac(request):
    id = request.GET['id']
    split_id = id.split('_')
    if len(split_id) > 1:
        api_id = id.split('_')[0]
        api = DB_case_set.objects.filter(id=api_id)[0]
        children = eval(api.children)
        for i in children:
            if i['id'] == id:
                children.remove(i)
                break
        api.children = str(children)
        api.save()
    else:  # 说明删除的就是一个一级节点：接口
        DB_case_set.objects.filter(id=id).delete()
    return get_apis(request)

# def remove_ac(request):
#     pro_ject_id=request.GET['pro_ject_id']
#     dck_id=DB_project_list.objects.filter(id=pro_ject_id)[0].dck
#     if dck_id[-1] in '_':
#         DB_case_set.objects.filter(id=id).delete()
#


# 新增配置
def add_configure(request):
    id = request.GET['id']
    api = DB_case_set.objects.filter(id=id)[0]
    children = eval(api.children)
    cid = int(children[-1]['id'].split('_')[1]) + 1 if children else 1
    children.append({"do_time": "after", "type": "configure", "label": "新配置", "method": "", "select": "", "value": "",
                     "id": "%s_%d" % (id, cid)})
    api.children = str(children)
    api.save()
    return get_apis(request)


# 保存配置
def save_configure(request):
    configure = json.loads(request.body.decode('utf-8'))
    api_id = configure['id'].split('_')[0]
    api = DB_case_set.objects.filter(id=api_id)[0]
    children = eval(api.children)  # [{},{},{}]
    for i in range(len(children)):
        if children[i]['id'] == configure['id']:
            children[i] = configure
            break
    else:
        children.append(configure)
    api.children = str(children)
    api.save()
    return get_apis(request)


# 上移配置
def up_configure(request):
    configure_id = request.GET['seting_confing_id']
    api_id = DB_case_set.objects.filter(id=configure_id.split('_')[0])[0]
    children = eval(api_id.children)
    for configure in range(len(children)):
        if children[configure]['id'] == configure_id:
            if configure > 0:
                children[configure], children[configure - 1] = children[configure - 1], children[configure]
                break
    api_id.children = str(children)
    api_id.save()
    return get_apis(request)


def down_configure(request):
    configure_id = request.GET['seting_confing_id']
    api_id = DB_case_set.objects.filter(id=configure_id.split('_')[0])[0]
    children = eval(api_id.children)
    for configure in range(len(children)):
        if children[configure]['id'] == configure_id:
            if configure < len(children) - 1:
                children[configure], children[configure - 1] = children[configure - 1], children[configure]
                break
    api_id.children = str(children)
    api_id.save()
    return get_apis(request)


#
# 上调-接口
def up_api(request):
    api_id = int(request.GET['api_id'])
    pro_ject_id = request.GET['pro_ject_id']
    all_api = DB_case_set.objects.filter(project_id=pro_ject_id)
    '''最外层接口id替换'''
    for i in range(len(all_api)):
        if all_api[i].id == api_id:  # 找到了
            if i > 0:
                all_api[i].id, all_api[i - 1].id = all_api[i - 1].id, all_api[i].id
                children = eval(all_api[i].children)
                '''最里层接口id替换'''
                for j in range(len(children)):
                    old_cid = children[j]['id'].split('_')[1]
                    children[j]['id'] = '%d_%s' % (all_api[i].id, old_cid)
                all_api[i].children = str(children)
                children = eval(all_api[i - 1].children)
                for j in range(len(children)):
                    old_cid = children[j]['id'].split('_')[1]
                    children[j]['id'] = '%d_%s' % (all_api[i - 1].id, old_cid)
                all_api[i - 1].children = str(children)
                all_api[i].save()
                all_api[i - 1].save()
                break
    return get_apis(request)


# 下降-接口
def down_api(request):
    api_id = int(request.GET['api_id'])
    pro_ject_id = request.GET['pro_ject_id']
    all_api = DB_case_set.objects.filter(project_id=pro_ject_id)
    for i in range(len(all_api)):
        if all_api[i].id == api_id:  # 找到了
            if i < len(all_api) - 1:
                all_api[i].id, all_api[i + 1].id = all_api[i + 1].id, all_api[i].id

                children = eval(all_api[i].children)
                for j in range(len(children)):
                    old_cid = children[j]['id'].split('_')[1]
                    children[j]['id'] = '%d_%s' % (all_api[i].id, old_cid)
                all_api[i].children = str(children)

                children = eval(all_api[i + 1].children)
                for j in range(len(children)):
                    old_cid = children[j]['id'].split('_')[1]
                    children[j]['id'] = '%d_%s' % (all_api[i + 1].id, old_cid)
                all_api[i + 1].children = str(children)

                all_api[i].save()
                all_api[i + 1].save()
                break
    return get_apis(request)


# 保存接口
def save_api(request):
    api_id = json.loads(request.body.decode('utf-8'))
    DB_case_set.objects.filter(id=api_id['id']).update(**api_id)
    return get_apis(request)


# 运行接口
def send_api(request):
    api = json.loads(request.body.decode('utf-8'))
    pro_ject_id = request.GET['pro_ject_id']
    s = Send_Api(api,{},api['children'])
    response_data = s.index()
    return HttpResponse(json.dumps(response_data),content_type='application/json')

# 上传接口文件
def upload_binary_file(request):
    IdCard = request.GET['ApiID']
    file = request.FILES.get('binary_file', None)
    filename = f'{IdCard}{file}'
    fp = open('api_App/static/tmp/' + filename, 'wb+')
    for i in file.chunks():
        fp.write(i)
    fp.close()
    DB_case_set.objects.filter(id=int(IdCard)).update(binary_file=filename)
    return HttpResponse('')


# 上传fd文件
def upload_fd_file(request):
    IdCard = request.GET['api_id']
    file = request.FILES.get('fd_file', None)
    filename = f'{IdCard}{file}'
    fp = open('api_App/static/tmp/' + filename, 'wb+')
    for i in file.chunks():
        fp.write(i)
    fp.close()
    return HttpResponse('上传成功')


# 获取可用变量
def get_user_par(request):
    api_id = request.GET['api_id']
    pro_ject_id = request.GET['pro_ject_id']
    res = ''
    apis = DB_case_set.objects.filter(project_id=pro_ject_id, id__lt=int(api_id))
    for i in apis:
        children = eval(i.children)
        for j in children:
            if j['method'] == '提取':
                res += f'{i.label + j["value"]}' + '\n'
    return HttpResponse(res)


# 运行所勾选用例
def doing_api(request):
    project_id = request.GET['pro_ject_id']
    doing_api = DB_project_list.objects.filter(id=int(project_id))[0].doing_api
    return HttpResponse(doing_api)


# 执行大用例
def run(request='',project_id=''):
    try:
        if request:
            project_id = request.GET['pro_ject_id']
        dck = DB_project_list.objects.filter(id=int(project_id))[0].dck.split(',')
        TQ = {}
        # 生成报告
        report = DB_report.objects.create()
        report.pro_ject_id = project_id
        report.create_time = time.strftime('%Y-%m-%d %H:%M')
        apis_result = []
        for i in range(len(dck)):
            if dck[i] and '_' not in dck[i]:  # 证明这个是接口
                need_children = []
                for j in range(i + 1, len(dck)):
                    if '%s_' % dck[i] in dck[j]:
                        need_children.append(dck[j])
                    else:
                        break
                # 实际去请求该接口了
                api = list(DB_case_set.objects.filter(id=int(dck[i])).values())[0]  # api此时是个字典
                DB_project_list.objects.filter(id=int(project_id)).update(doing_api=api['label'])
                api['children'] = eval(api['children'])
                children = []
                for c in api['children']:
                    if c['id'] in need_children:
                        children.append(c)
                api['params'] = eval(api['params'])
                api['headers'] = eval(api['headers'])
                api['payload_fd'] = eval(api['payload_fd'])
                api['payload_xwfu'] = eval(api['payload_xwfu'])
                # 调用类执行了
                s = Send_Api(api, TQ, children)
                response_data = s.index()
                url = s.make_Url()
                TQ = response_data['TQ']
                apis_result.append(response_data['REPORT'])
                if response_data ['REPORT'] ['result'] == False:
                    report.all_result = False
        report.apis_result = str(apis_result)
        report.save()
        return HttpResponse(str(report.all_result))
    except:
        return HttpResponse('请勾选运行接口')


# 清空所有报告
def clear_all_reports(request):
    pro_ject_id = request.GET['pro_ject_id']
    DB_report.objects.filter(pro_ject_id=pro_ject_id).delete()
    return HttpResponse('')


# 获取所有报告
def get_all_reports(request):
    pro_ject_id = request.GET['pro_ject_id']
    all_reports = list(DB_report.objects.filter(pro_ject_id=pro_ject_id).values())[::-1]
    for all_report in all_reports:
        all_report['apis_result'] = eval(all_report['apis_result'])
    return HttpResponse(json.dumps(all_reports), content_type='application/json')




def test_A(request):
    print('A被调用')
    return HttpResponse(json.dumps({"a":111,"b":{"c":11}}),content_type='application/json')



def test_B(request):
    print('B被调用')
    return HttpResponse(json.dumps({"a":222,"b":{"c":22}}),content_type='application/json')

#
#
#
# # 保存接口
# def save_api(request):
#     api = json.loads(request.body.decode('utf-8'))
#     DB_apis.objects.filter(id=api['id']).update(**api)
#     return get_apis(request)
